package com.demo2do.wechatmcs.web.controller.wechat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.wechat.entity.cfg.JsConfig;
import com.demo2do.wechatmcs.entity.token.JsTicket;
import com.demo2do.wechatmcs.entity.token.Token;
import com.demo2do.wechatmcs.handle.WechatTokenHandler;
import com.fasterxml.jackson.annotation.JsonView;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/wechat")
public class WechatTokenController {
    
    private static final Logger logger = LoggerFactory.getLogger(WechatTokenController.class);
    
    @Autowired
    private WechatTokenHandler wechatTokenHandler;
    
    /**
     * request wehcat access token
     * 
     * @return
     */
    @JsonView
    @RequestMapping(value="/access-token", method = RequestMethod.GET)
    public HttpResult requestAccessToken() {
    
    HttpResult httpResult = new HttpResult();

    logger.trace("#requestAccessToken - Trying to request global access_token ... ");
    
    Token token = wechatTokenHandler.requestAccessToken();
    
    return httpResult.success().data(token.descibe());
    }

    /**
     * request wehcat jsConfig
     * 
     * @param curl
     * @return
     */
    @JsonView
    @RequestMapping(value="/js-ticket", method = RequestMethod.GET, params="curl")
    public HttpResult requestJsTicket(@RequestParam(value = "curl") String curl) {
        
        HttpResult httpResult = new HttpResult();
        
        logger.trace("#requestJsTicket - Trying to request wechat js_ticket ... ");
        
        JsTicket jsTicket = wechatTokenHandler.requestJsTicket();
        
        if(jsTicket.isValid()) {
            
            JsConfig jsConfig = new JsConfig(jsTicket.getAppid(), jsTicket.getTicket(), curl);
            
            return httpResult.success()
                             .data("wechatJsConfig", jsConfig);
            
        }
        
        return httpResult.fail("500").message("INVALID_JS_TICKET");
        
    }

}
